import React, { useState, useEffect, useRef } from "react";
import { connect } from 'umi';
import { Row, Col, Card, Space, Input, Button } from 'antd';
import { backgroundObj } from '@/utils/utils'
import CopyToClipboard from 'react-copy-to-clipboard';
import QRCode from 'react-qr-code';
import html2canvas from 'html2canvas';
import './index.less'

const liveInfo = (props) => {
  const { detail = {}, dispatch } = props
  const [data, setData] = useState({})
  const [shareInfo, setShareInfo] = useState({})
  const { id, goodsType, startTime } = detail
  const [shareImage, setShareImg] = useState('')
  const account = JSON.parse(window.localStorage.getItem('account')) || {}
  const [selectIndex, setSelectIndex] = useState(0)
  const { username, profile } = account
  const containerRef = useRef(null);
  const { wechatUrl = '', frontImage, body
  } = shareInfo
  const convertToImage = () => {
    const setup = {
      useCORS: true, // 使用跨域
    };
    if (containerRef.current) {
      html2canvas(containerRef.current, setup)
        .then((canvas) => {
          // 将canvas转化为图片路径
          const dataUrl = canvas.toDataURL('image/png');
          // dataUrl 包含转化后的图片路径
          setShareImg(dataUrl)
        })
        .catch((error) => {
          console.error('转化失败', error);
        });
    }
  };
  const RenderImage = () => {
    return (<div ref={containerRef} className='shareImage_image_card'>
      <div className='shareImage_image_cardBg'></div>
      <div className='shareImage_image_title'>
        <div className='shareImage_image_profile' style={backgroundObj(profile)}></div>
        <div className='shareImage_image_profileContent'>
          <div className='shareImage_image_username'>{username}</div>
          <div className='shareImage_image_desc'>邀请你一起观看</div>
        </div>
      </div>
      <div className='shareImage_image_cover'>
        <div className='shareImage_image_coverImg' style={backgroundObj(frontImage)}></div>
      </div>
      <div className='shareImage_time_code'>
        <div className='shareImage_time_timeInfo'>
          <div className='shareImage_time_timeTitle'>开播时间：</div>
          <div className='shareImage_time_timeCount'>{startTime}</div>
        </div>
        <div className='shareImage_time_codecode'> <QRCode className='shareImage_image_imgcode' value={wechatUrl} /></div>
      </div>
    </div>)
  }
  const list = [RenderImage]
  useEffect(() => {
    if (shareInfo.wechatUrl) {
      convertToImage()
    }
  }, [shareInfo])
  useEffect(() => {
    if (id) {
      fetchPushAndLiveUrl()
      fetchShareInfo()
    }
  }, [id])
  const fetchPushAndLiveUrl = () => {
    dispatch({
      type: 'liveStreaming/fetchPushAndLiveUrl',
      payload: {
        goodsId: id,
        goodsType: 'directLive',

      },
      callback: (e) => {
        const { pushUrl, playUrl } = e
        setData({
          pushUrl, playUrl
        })
      }
    })
  }
  const fetchShareInfo = () => {
    dispatch({
      type: 'liveStreaming/fetchGetShareInfo',
      payload: {
        shareId: id,
        shareType: 'goods',
        subType: 'directLive',
        organizationId: window.localStorage.getItem(
          'organizationId',
        )
      },
      callback: (e) => {
        setShareInfo(e.shareInfo)
      }
    })

  }
  const download = (src) => {
    let canvas = document.createElement('canvas'); //创建canvas DOM元素
    const ctx = canvas.getContext('2d');
    const img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');
    img.setAttribute('referrerpolicy', 'no-referrer'); // 不用带 referer 所有的防止外链的行为都会失效
    img.src = src;
    img.onload = function () {
      canvas.height = img.height;
      canvas.width = img.width;
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const dataURL = canvas.toDataURL('image/png');
      const elink = document.createElement('a');
      elink.href = dataURL;
      elink.download = `${body}.jpg`; // 图片name
      elink.click();
      canvas = null;
    }
  }
  const { pushUrl, playUrl
  } = data

  return (
    <Card title='obs'>
      <Space style={{ width: '100%' }} direction='vertical'>
        <div className='obs_key_box'>
          服务器地址:
        </div>
        <Row>
          <Col span={20}><Input disabled value={pushUrl} /> </Col>
          <Col span={4}>
            <CopyToClipboard text={pushUrl} onCopy={() => {
              notification.success({
                message: '温馨提示',
                description: '复制成功',
              });
            }}>
              <Button type='link'>复制</Button>
            </CopyToClipboard>
          </Col>
        </Row>
        <div className='obs_key_box' style={{ color: '#999999' }}>
          请在obs推流设置中，将上述内容替换，完成即可开播
        </div>
        <div className='obs_key_box'>
          播放地址:
        </div>
        <Row>
          <Col span={20}><Input disabled value={playUrl} /> </Col>
          <Col span={4}>
            <CopyToClipboard text={playUrl} onCopy={() => {
              notification.success({
                message: '温馨提示',
                description: '复制成功',
              });
            }}>
              <Button type='link'>复制</Button>
            </CopyToClipboard>
          </Col>
        </Row>
        <div className='obs_key_box'>
          分享地址:
        </div>
        <Row>
          <Col span={20}><Input disabled value={wechatUrl} /> </Col>
          <Col span={4}>
            <CopyToClipboard text={wechatUrl} onCopy={() => {
              notification.success({
                message: '温馨提示',
                description: '复制成功',
              });
            }}>
              <Button type='link'>复制</Button>
            </CopyToClipboard>
          </Col>
        </Row>
        <div className='obs_key_box'>
          分享卡片:
        </div>
        <div className='shareImage_image_margin'>
          <div className='shareImage_image_long'><img src={shareImage} /></div>
          <Button type="link" onClick={() => download(shareImage)}>下载</Button>
        </div>
        <div className='shareImage_imagre_box'>
          {
            list.map((Item, index) => {
              if (index === selectIndex) {
                return <Item key={index}></Item>
              }
              else {
                return null
              }
            })
          }
        </div>
      </Space>
    </Card>

  )
}
export default connect(({ loading }) => ({
  loading: loading.effects['liveStreaming/fetchPushAndLiveUrl']
}))(liveInfo);;


